package com.xsprite.managesys.service;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

public class ServersManager {
	private static ServersManager instance;
	private List<ServerConfig> serverconfigs = new ArrayList<ServerConfig>();
	private Map<String, ServerConfig> mapServer = new HashMap<String, ServerConfig>();

	public static ServersManager getInstance() {
		if (instance == null) {
			instance = new ServersManager();
		}
		return instance;
	}
	
	public List<ServerConfig> getServerConfigs(){
		return serverconfigs;
	}
	
	public ServerConfig getServerConfigByName(String serverName){
		return mapServer.get(serverName);
	}

	public void loadServers(String path) throws Exception{
		SAXBuilder saxBuilder=new SAXBuilder(false);
		saxBuilder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        saxBuilder.setExpandEntities(false);
        File file = new File(path);
        Document doc = saxBuilder.build(file);
        Element root = doc.getRootElement();
        List<Element> servers = root.getChildren("server");
        for(Element serverEle : servers){
        	ServerConfig serverConfig = new ServerConfig();
        	serverConfig.setServerName(serverEle.getChild("server-name").getText());
        	serverConfig.setServerId(serverEle.getChild("server-id").getText());
        	serverConfig.setUrl(serverEle.getChild("server-url").getText());
        	serverConfig.setPort(serverEle.getChild("port").getText());
        	serverConfig.setDataName(serverEle.getChild("data-name").getText());
        	serverConfig.setUserName(serverEle.getChild("user-name").getText());
        	serverConfig.setPassName(serverEle.getChild("user-pass").getText());
        	serverconfigs.add(serverConfig);
        	mapServer.put(serverConfig.getServerName(), serverConfig);
        }
	}
}
